//
// Created by xinhua on 2021/9/28.
//
#include "ShaderUtil.h"

static std::vector<ShaderName> shadersArray;
static std::map<std::string, Shader> shaderCacheMap;

ShaderName::ShaderName(const char* name, const char* vsFilePath, const char* fsFilePath) {
    this->name = name;
    this->vsFilePath = vsFilePath;
    this->fsFilePath = fsFilePath;
}

void ShaderUtil::setShaders(std::vector<ShaderName> shaders) {
    ShaderName def(DEFAULT_SHADER_NAME, VSHADER_FILE_PATH, FSHADER_FILE_PATH);
    shaders.push_back(def);
    shadersArray = shaders;
}

void ShaderUtil::initShaders() {
    log_info("initShaders");

    std::vector<ShaderName>::iterator it;
    for(it = shadersArray.begin(); it != shadersArray.end(); it ++){
        const char * name = it.base()->name;
        const char * vsFilePath = it.base()->vsFilePath;
        const char * fsFilePath = it.base()->fsFilePath;
        std::string apdVsFilePath = "";
        std::string apdFsFilePath = "";
        apdVsFilePath = apdVsFilePath.append(vsFilePath);
        apdFsFilePath = apdFsFilePath.append(fsFilePath);
        log_info("compile shader: %s\nvsFile:%s\nfsFile:%s", name, apdVsFilePath.c_str(), apdFsFilePath.c_str());

        Shader shader(apdVsFilePath.c_str(), apdFsFilePath.c_str());
        shader.initAttributeArrays();
        shaderCacheMap.insert(std::make_pair(name, shader));
    }
}

Shader ShaderUtil::getShaderByName(const char* name) {
    int size = shaderCacheMap.size();
    if(size == 0){
        initShaders();
    }
    if(shaderCacheMap.count(name) > 0){
        return shaderCacheMap[name];
    }
    assert(false);
    return shaderCacheMap[DEFAULT_SHADER_NAME];
}

